package org.jeecg.modules.demo.signatureCA.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;



public class JsonUtil {

	public static List listByJsonVar(String str, Class entity) {
		JSONArray jsonArray = JSONArray.fromObject(str);
		return JSONArray.toList(jsonArray,entity);
	}

	public static String listToJsoin(List list){
		JSONArray ja = JSONArray.fromObject(list);
		//System.out.print(ja.toString());
		return ja.toString();

	}
	public static String mapToJson(Map map){
		JSONObject jo = JSONObject.fromObject(map);
		return jo.toString();
	}

	public static String objectToJson(Object obj){
		JSONObject jo = JSONObject.fromObject(obj);
		return jo.toString();
	}

	public static String elementToJson(Element element){
		JSONObject jo = JSONObject.fromObject(element);
		return jo.toString();
	}

	public static String stringToJson(String str){
		JSONObject jo = JSONObject.fromObject(str);
		return jo.toString();
	}

	 /**
	  * 将一个实体类对象转化成JSON数据格式,等效于object2json
	  * @param obj 实体类对象
	  * @return JSON数据格式字符串
	  */
	 public static String pojo2json(Object obj){
	  return JSONObject.fromObject(obj).toString(1);
	 }

	 /**
	  * 将数组集合等对象转换成JSON字符串
	  * @param list
	  * @return
	  */
	 public static String object2json(Object list){
	  return JSONSerializer.toJSON(list).toString(1);
	 }

	 /**
	  * 将Map准换为JSON字符串,等效于object2json()
	  * @param map map集合
	  * @return JSON字符串
	  */
	 public static String map2json(Map<?,?> map){
	  JSONObject object = JSONObject.fromObject(map);
	  return object.toString(1);
	 }

	 /**
	  * 将xml字符串转换为JSON字符串
	  * @param xmlString xml字符串
	  * @return JSON对象
	  */
	 public static String xml2json(String xmlString){
	  XMLSerializer xmlSerializer = new XMLSerializer();
	  JSON json = xmlSerializer.read(xmlString);
	  return json.toString(1);
	 }

	 /**
	  * 将xmlDocument转换为JSON对象
	  * @param xmlDocument XML Document
	  * @return JSON对象
	  */
	 public static String xml2json(Document xmlDocument){
	  return xml2json(xmlDocument.toString());
	 }

	    /**
	     * 读取XML文件准换为JSON字符串
	     * @param xmlFile  XML文件
	     * @return JSON字符串
	     */
	  public static String xmlFile2json(String xmlFile) {
	        //InputStream is = this.getClass().getResourceAsStream(xmlFile);
	        String xml;
	        String json = null;
	        try {
	        	File file = new File(xmlFile);
			    //FileInputStream in = new FileInputStream(file);
			    XMLSerializer xmlSerializer = new XMLSerializer();
			    JSON js = xmlSerializer.readFromFile(file);
			    json = js.toString(1);
	            //xml = IOUtils.toString(in);
	            //json = xml2json(xml);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return json;
	    }



	 /**
	  * 将Json格式的字符串转换成指定的对象返回
	  * @param jsonStr 要转化的Json格式的字符串
	  * @param javaBean 指定转化对象类型
	  * @return 转化后的对象
	  */
	 public static Object json2pojo(String jsonStr,Class javaBean){
	  JSONObject jsonObj = JSONObject.fromObject(jsonStr);
	  Object obj = JSONObject.toBean(jsonObj, javaBean);
	  return obj;
	 }

	 /**
	  * 将Json格式的字符串转换成Map对象
	  * @param jsonString JSON数据格式字符串
	  * @return map集合
	  */
	 public static Map<String, Object> json2Map(String jsonString) {
	        return (Map<String, Object>) json2pojo(jsonString,Map.class);
	    }

	 /**
	  * 将Json格式的字符串转换成对象数组返回
	  * @param jsonString JSON数据格式字符串
	  * @return 对象数组
	  */
	 public static Object[] json2ObjectArray(String jsonString) {
	        JSONArray jsonArray = JSONArray.fromObject(jsonString);
	        return jsonArray.toArray();
	    }

	 /**
	  * 将Json格式的字符串转换成指定对象组成的List返回
	  * @param jsonString JSON数据格式字符串
	  * @param pojoClass 指定转化对象类型
	  * @return list集合
	  */
	 public static List jsonArray2List(String jsonString, Class pojoClass){
	  JSONArray jsonArray = JSONArray.fromObject(jsonString);
	  return jsonArray.toList(jsonArray,pojoClass);
	 }

	 /**
	  * pojo，集合，数组等对象转换成XML字符串
	  * @param obj
	  * @return
	  */
	 public static String obj2xml(Object obj){
	  XMLSerializer xmlSerializer = new XMLSerializer();
	  return xmlSerializer.write(JSONSerializer.toJSON(obj));
	 }

	 /**
	  * JSON(数组)字符串转换成XML字符串
	  * @param jsonString
	  * @return
	  */
	 public static String json2xml(String jsonString){
	  XMLSerializer xmlSerializer = new XMLSerializer();
	  return xmlSerializer.write(JSONSerializer.toJSON(jsonString));
	//  return xmlSerializer.write(JSONArray.fromObject(jsonString));//这种方式只支持JSON数组
	 }

	 private static void gererateFile(String str, String path) {
		    File file = new File(path);
		    try {
		        file.createNewFile();
		        PrintStream printStream = new PrintStream(new FileOutputStream(file));
		        printStream.println(str);
		    } catch (IOException e) {
		        e.printStackTrace();
		    }
		}

	 public static void gererateXmlFile(String xmlStr, String xmlFilePath)
	         throws Exception {
	     Document doc = DocumentHelper.parseText(xmlStr);
	     OutputFormat format = new OutputFormat("", true);
	     format.setEncoding("utf-8");
	     StringWriter out = new StringWriter();
	     XMLWriter xmlWriter = new XMLWriter(out, format);
	     xmlWriter.write(doc);
	     xmlWriter.flush();
	     gererateFile(out.toString(), xmlFilePath);
	 }

	 public static String convertJson(String str){
		if("".equals(str) || str==null) return "";
		String[] s = str.replace("=", "\":\"").split("&");
		JSONArray ja = JSONArray.fromObject(s);
		return ja.toString().replace("\\", "").replace("[", "{").replace("]", "}");
	 }

	public static void main(String[] args) {
//		List list = new ArrayList();
//		Example e1 = new Example();
//		e1.setId(1l);
//		e1.setName("tom");
//		e1.setPassword("123");
//		e1.setSex("男");
//		e1.setAge(18);
//
//		JSONObject jo = JSONObject.fromObject(e1);
//		System.out.println("objtojson----"+jo.toString());
//
//		Example e2 = new Example();
//		e2.setId(1l);
//		e2.setName("tom");
//		e2.setPassword("123");
//		e2.setSex("女");
//		e2.setAge(18);
//
//		list.add(e1);
//		list.add(e2);
//
//
//		JQGrid jqgrid = new JQGrid();
//		jqgrid.setPage(1);
//		jqgrid.setRecords(30);
//		jqgrid.setTotal(20);
//		jqgrid.setRows((ArrayList<Object>) list);

//		String strList = ObjectTOJqgrid(jqgrid);
//		System.out.println(strList + "-----listToJson----");


//		String a ="[{\"zhibbm\":\"1\",\"fuh\":\"-\",\"shangxz\":\"6000\",\"xiaxz\":\"3000\",\"fenzbm\":0},{\"zhibbm\":\"6\",\"fuh\":\"-\",\"shangxz\":\"0.2\",\"xiaxz\":\"1\",\"fenzbm\":0},{\"zhibbm\":\"3\",\"fuh\":\"-\",\"shangxz\":\"0.1\",\"xiaxz\":\"2\",\"fenzbm\":0},{\"zhibbm\":\"5\",\"fuh\":\"-\",\"shangxz\":\"2\",\"xiaxz\":\"1\",\"fenzbm\":0}]";
//		JSONArray jsonArray = JSONArray.fromObject(a);
//		List list1 = JSONArray.toList(jsonArray);
//		System.out.println(list1.toString() + "-----listToJson----");

		Map map = new HashMap();
		map.put(1, "qq");
		map.put(2, "aa");
		String strMap = mapToJson(map);
		System.out.println(strMap + "-----listToJson----");

//		String str = "[{\"s2\":[{\"SERVICEID\":\"s2\"},{\"APPID\":\"2\"},{\"SERVICENAME\":\"globalCache\"},{\"SERVICETYPE\":\"1\"},{\"SERVICEADDR\":\"http://10.1.22.223:8080/globalCache/restful/\"},{\"SERVICEDESC\":\"缂撳瓨鏈嶅姟\"},{\"VERSION\":\"v.1.0\"},{\"LASTUPDATETIME\":\"2014-02-20 12:06\"}],\"s1\":[{\"SERVICEID\":\"s1\"},{\"APPID\":\"2\"},{\"SERVICENAME\":\"globalCache\"},{\"SERVICETYPE\":\"1\"},{\"SERVICEADDR\":\"http://10.1.22.222:8080/globalCache/restful/\"},{\"SERVICEDESC\":\"缂撳瓨鏈嶅姟\"},{\"VERSION\":\"v.1.0\"},{\"LASTUPDATETIME\":\"2014-02-20 19:06\"}]}]";
//		JSONArray jo = JSONArray.fromObject(str);
//		List list = (List)JSONArray.toList(jo);
//		Iterator it = list.iterator();
//		while(it.hasNext()){
//			System.out.println("objtojson----"+it.next());
//		}

//		String[] str = {"1212","12123","1231231"};
//		System.out.println(object2json(str));

//		String str = "page=1&start=0&limit=2";
//
//
//
//		System.out.println(convertJson(str));
	}
}

